package com.hntxk.cqzd.diacrisis.service.impl;

import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisExistingChild;
import com.hntxk.cqzd.diacrisis.model.DiacrisisAllModel;
import com.hntxk.cqzd.diacrisis.service.DiacrisisExistingChildService;
import com.hntxk.sp.log.model.ActionLog;
import com.hntxk.sp.log.model.ActionType;
import com.hntxk.sp.util.LogRecordUtil;
import com.hntxk.sp.util.LoginUserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service("diacExistingChildService")
@Transactional(rollbackFor = Exception.class)
public class DiacrisisExistingChildServiceImpl extends BaseServiceImpl<TblDiacrisisExistingChild> implements DiacrisisExistingChildService {

    private static String MAPPER_NAMESPACE="com.hntxk.cqzd.diacrisis.mapper.DiacrisisExistringChildMapper.";

    public DiacrisisExistingChildServiceImpl() {
        super(MAPPER_NAMESPACE);
    }


    @Override
    public ResultModel<DiacrisisAllModel> insert(DiacrisisAllModel diacrisisAllModel) {
        List<TblDiacrisisExistingChild> existingChild = diacrisisAllModel.getExistingChild();

        for (TblDiacrisisExistingChild diacrisisExistingChild : existingChild) {
            getPrimaryKey(diacrisisExistingChild);
            diacrisisExistingChild.setDiacrisisId(diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId());
            super.insert(MAPPER_NAMESPACE + "insert", diacrisisExistingChild);
            if (LoginUserUtil.isLogin()) {
                LogRecordUtil.addLog(new ActionLog(TblDiacrisisExistingChild.class, diacrisisExistingChild.getChildId() + "", "12",
                        ActionType.ADD, "新增现存孩信息：" + diacrisisExistingChild.getChildAge() + "[ " + diacrisisExistingChild.getChildBirthday() + " ]"));
            }
        }
        return ResultModel.empty();
    }

    @Override
    public ResultModel<DiacrisisAllModel> update(DiacrisisAllModel diacrisisAllModel) {

        //获取外键id
        Long diacrisisId = diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId();
        //根据外键查询库中是否有值
        List<TblDiacrisisExistingChild> childs = getByFkId(diacrisisId);
        if(childs!=null&&childs.size()>0) {
            //根据外键删除此表的数据
            delete(MAPPER_NAMESPACE+"deleteByFkId",diacrisisId);
        }
        return insert(diacrisisAllModel);
    }



    @Override
    public List<TblDiacrisisExistingChild> getByFkId(Long id) {
        TblDiacrisisExistingChild tblDiacrisisExistingChild=new TblDiacrisisExistingChild();
        tblDiacrisisExistingChild.setDiacrisisId(id);
        List<TblDiacrisisExistingChild> list = (List<TblDiacrisisExistingChild>) query(MAPPER_NAMESPACE + "getByFkId", tblDiacrisisExistingChild);
        return list;
    }

}
